﻿//	Ordinaire.Security.UserManager
//	Copyright (c) 2011 Jonathan Loe
//
//	MIT license (http://en.wikipedia.org/wiki/MIT_License)
//
//	Permission is hereby granted, free of charge, to any person obtaining a copy
//	of this software and associated documentation files (the "Software"), to deal
//	in the Software without restriction, including without limitation the rights 
//	to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
//	of the Software, and to permit persons to whom the Software is furnished to do so, 
//	subject to the following conditions:
//
//	The above copyright notice and this permission notice shall be included in all 
//	copies or substantial portions of the Software.
//
//	THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, 
//	INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
//	PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE 
//	FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
//	ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

using System;
using System.Collections.Generic;
using System.Data.Linq;
using System.Linq;
using System.Security.Cryptography;
using System.Text;

using Ordinaire.Db.Linq;
using Ordinaire.Security.Model;

namespace Ordinaire.Security
{
    public class UserManager
    {
        #region Variables

        /// <summary>
        /// Singleton instance
        /// </summary>
        protected static readonly UserManager _instance = new UserManager();

        #endregion

        #region Constructor

        /// <summary>
        /// Hidden constructor
        /// </summary>
        private UserManager() {  }

        #endregion

        #region Properties

        /// <summary>
        /// Returns singleton instance.
        /// </summary>
        public static UserManager Instance
        {
            get
            {
                return _instance;
            }
        }

        #endregion

        #region Public methods

        /// <summary>
        /// Authenticates specified userid and password.
        /// </summary>
        /// <param name="id">userid</param>
        /// <param name="password">password</param>
        /// <returns>Corresponding user profile else null</returns>
        public User Authenticate(string id, string password)
        {
            if (String.IsNullOrEmpty(id))
            {
                throw new ArgumentNullException(String.Format(ExceptionMessage.IsNullOrEmpty, "id"));
            }

            if (String.IsNullOrEmpty(password))
            {
                throw new ArgumentNullException(String.Format(ExceptionMessage.IsNullOrEmpty, "password"));
            }

            string hash = Cryptographer.Hash(password);

            using (OrdinaireContext context = new OrdinaireContext())
            {
                var query = from q in context.Users
                            where q.Id == id && q.Password == hash
                            select q;

                try
                {
                    User user = query.Single<User>();
                    return user;
                }
                catch (Exception)
                {
                    return null;
                }
            }
        }

        /// <summary>
        /// Creates new user.
        /// </summary>
        /// <param name="id">desired user id</param>
        /// <param name="name">desired name</param>
        /// <param name="password">generated random password</param>
        /// <returns>instance of User class</returns>
        public User CreateUser(string id, string name, out string password)
        {
            using (OrdinaireContext context = new OrdinaireContext())
            {
                // Generate random password
                password = GenerateRandomPassword();

                // Create new user
                User user     = new User();
                user.Id       = id;
                user.Name     = name;
                user.Password = Cryptographer.Hash(password);

                context.Users.InsertOnSubmit(user);
                context.SubmitChanges();

                return user;
            }
        }

        /// <summary>
        /// Changes password of specified userid.
        /// </summary>
        /// <param name="id">userid</param>
        /// <param name="currentPassword">current password</param>
        /// <param name="newPassword">new password</param>
        /// <returns>true if update is successful</returns>
        public bool ChangePassword(string id, string currentPassword, string newPassword)
        {
            User user = Authenticate(id, currentPassword);
            if (user == null)
            {
                return false;
            }

            using (OrdinaireContext context = new OrdinaireContext())
            {
                try
                {
                    // Retrieve current record for successful update using the same context
                    var query = from q in context.Users
                                where q.Id == id
                                select q;

                    user = query.Single<User>();
                    user.Password = Cryptographer.Hash(newPassword);

                    context.SubmitChanges();
                }
                catch (Exception) { return false; }
            }

            return true;
        }

        /// <summary>
        /// Generates random password of 8 characters in length.
        /// </summary>
        /// <returns>generated password</returns>
        public string GenerateRandomPassword()
        {
            // Set default length as 8
            return GenerateRandomPassword(8);
        }

        /// <summary>
        /// Generates random password of specified length.
        /// </summary>
        /// <param name="length">desired number of characters</param>
        /// <returns>generated password</returns>
        public string GenerateRandomPassword(int length)
        {
            string guid = System.Guid.NewGuid().ToString();

            // Remove hyphens
            guid = guid.Replace("-", String.Empty);

            return guid.Substring(0, length);
        }

        /// <summary>
        /// Returns matching user of the specified userid.
        /// </summary>
        /// <param name="id">user id</param>
        /// <returns>the matching user</returns>
        public User Get(string id)
        {
            if (String.IsNullOrEmpty(id))
            {
                throw new ArgumentNullException(String.Format(ExceptionMessage.IsNullOrEmpty, "id"));
            }

            using (OrdinaireContext context = new OrdinaireContext())
            {
                try
                {
                    var query = from q in context.Users
                                where q.Id == id
                                select q;

                    User user = query.Single<User>();
                    return user;
                }
                catch (Exception)
                {
                    return null;
                }
            }
        }

        /// <summary>
        /// Returns all users.
        /// </summary>
        /// <returns>list of users</returns>
        public List<User> GetUsers()
        {
            List<User> users = new List<User>();

            using (OrdinaireContext context = new OrdinaireContext())
            {
                var query = from q in context.Users
                            select q;

                users = query.ToList<User>();
            }

            return users;
        }

        /// <summary>
        /// Return assigned roles of specified userid
        /// </summary>
        /// <param name="id">userid</param>
        /// <returns>list of roles</returns>
        public List<Role> GetRolesByUserid(string id)
        {
            List<Role> roles = new List<Role>();

            using (OrdinaireContext context = new OrdinaireContext())
            {
                var query = from ur in context.UserRoles
                            join r in context.Roles on ur.RoleId equals r.Id
                            where ur.UserId == id
                            select r;

                roles = query.ToList<Role>();
            }

            return roles;
        }

        /// <summary>
        /// Updates details of specified user.
        /// </summary>
        /// <param name="user">details of specified user</param>
        /// <returns>true if update is successful</returns>
        public bool Update(User user)
        {
            if (user == null)
            {
                throw new ArgumentNullException(String.Format(ExceptionMessage.IsNullOrEmpty, "user"));
            }

            if (String.IsNullOrEmpty(user.Id))
            {
                throw new ArgumentException(String.Format(ExceptionMessage.IsNullOrEmpty, "user.Id"));
            }

            using (OrdinaireContext context = new OrdinaireContext())
            {
                var query = from q in context.Users
                            where q.Id == user.Id
                            select q;

                User original = query.Single<User>();
                original.Name = user.Name;
                context.SubmitChanges();
            }

            return true;
        }

        #endregion
    }
}
